const express = require("express"),
  router = express.Router(),
  Core = require("@alicloud/pop-core"),
  query = require("../mysql"),
  moment = require("moment"),
  createRandom = require("../utils/createRandom"),
  verToken = require("../utils/token");
var client = new Core({
  accessKeyId: "LTAI4G3ndgvPeYJ8jMTLBPJj",
  accessKeySecret: "OTuNvHD8lZh2E5BXXZd4ZfyU1Fm5Aq",
  // securityToken: '<your-sts-token>', // use STS Token
  endpoint: "https://dysmsapi.aliyuncs.com",
  apiVersion: "2017-05-25",
});
var params = {
  SignName: "尼恩科技",
  TemplateCode: "SMS_221073298",
};
// 二级路由定义在router对象上
router.post("/code", async (req, res) => {
  const { userPhone, userName } = req.body;
  if (!userName || !userPhone)
    return res.send({ code: 500, msg: "姓名或者手机不能为空" });
  let sqlUser = `select userPhone from user where userName='${userName}';`;
  let userRes = await query(sqlUser);
  //   名字和手机不匹配
  // console.log(userRes[0].userPhone);
  if (userRes.length !== 1) {
    return res.send({
      code: 500,
      msg: "手机号码和名字不匹配，请检查或者联系管理员",
    });
  }
  const randomNum = createRandom(),
    PhoneNumbers = userPhone.toString();
  params.TemplateParam = JSON.stringify({ code: randomNum });
  params.PhoneNumbers = PhoneNumbers;
  let sqlCode = `UPDATE user SET phoneCode=${randomNum} where userPhone=${PhoneNumbers} and userName='${userName}';`;
  client.request("SendSms", params, { method: "POST" }).then(
    async (result) => {
      if (result.Message === "OK" && result.Code === "OK") {
        let sqlRes = await query(sqlCode);
        //   写入数据库
        if (sqlRes.affectedRows === 1) {
          res.send({ code: 200, msg: "发送成功" });
        } else {
          res.send({ code: 500, msg: "写入失败" });
        }
      } else {
        res.send({ code: 500, msg: "短信发送失败，请稍后重试" });
      }
    },
    (ex) => {
      // console.log(ex);
      res.status(500).send("未知错误，请稍后重试");
    }
  );
});
router.post("/", async (req, res) => {
  const { userName, userPhone, code } = req.body;
  // console.log(userName, userPhone, code);
  if (!userName || !userPhone || !code)
    return res.send({ code: 500, msg: "姓名，手机，验证码必填" });
  let sql = `select phoneCode,id from user where userPhone='${userPhone}' and userName='${userName}';`;
  sqlRes = await query(sql);
  const { phoneCode, id } = sqlRes[0];
  // console.log(typeof phoneCode);
  if (Number(code) === phoneCode && phoneCode !== null) {
    verToken.setToken(userName, id).then(async (token) => {
      let loginSql = `UPDATE user SET token='${token}',loginTime='${moment(
        new Date()
      ).format(
        "YYYY-MM-DD HH:mm:ss"
      )}' where userPhone=${userPhone} and userName='${userName}';`;
      let loginRes = await query(loginSql);
      if (loginRes.affectedRows === 1) {
        res.send({ code: 200, message: "登陆成功", token });
      } else {
        res.send({ code: 500, msg: "登陆失败，请重试" });
      }
    });
  } else {
    res.json({ code: 500, msg: "登陆失败,请检查验证码" });
  }
});
// 向外暴露router
module.exports = router;
